package com.wb.mas.utils.response;


import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class CustomResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private TypeAdapter<T> adapter;
    private Type mType;

    CustomResponseConverter(Gson gson, TypeAdapter<T> mAdapter, Type mType) {
        this.gson = gson;
        this.adapter = mAdapter;
        this.mType = mType;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        ErrorResponse errorResponse = new ErrorResponse();
        try {
            String body = value.string();
            JSONObject json = new JSONObject(body);
            int code = json.getInt("status");
            String msg = json.getString("message");
            if (200 == code) {
//此处的RESPCODE为你和后台约定返回的正常的responseCode
                return gson.fromJson(body, mType);
            } else {
                errorResponse = gson.fromJson(body, ErrorResponse.class);
                //ErrorResponse  为自定义的错误类
                //抛一个自定义ResultException 传入失败时候的状态码，和信息
                throw new ResultException(errorResponse.getStatus(), errorResponse.getMessage());
            }
        } catch (Exception e) {
//            return null;
            throw new ResultException(errorResponse.getStatus(), errorResponse.getMessage());
        } finally {
            value.close();
        }

    }
}
